package com.example.jimuyutabletcontrol.activity;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.example.jimuyutabletcontrol.R;
import com.example.jimuyutabletcontrol.adapter.clubadapter.Club;
import com.example.jimuyutabletcontrol.adapter.clubadapter.ClubAdapter;
import com.example.jimuyutabletcontrol.adapter.clubadapter.FixedGridLayoutManager;
import com.example.jimuyutabletcontrol.adapter.clubadapter.RecyclerItemClickListener;
import com.example.jimuyutabletcontrol.database.DBHelperSend;
import com.example.jimuyutabletcontrol.database.TaskContainer;
import com.marcoscg.headerdialog.HeaderDialog;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

public class CheckData extends AppCompatActivity {

    /*
    private View view;
    private EditText checkDataLatitude;
    private EditText checkDataLongtitude;
    private EditText checkDataEditSpeed;
    private EditText checkDataEditDepth;
    private AlertDialog alertDialog;
    */

    private HeaderDialog headerDataDialog;
    private int mPosition;

    int scrollX = 0;

    private List<Club> clubList;

    RecyclerView rvClub;

    HorizontalScrollView headerScroll;

    ClubAdapter clubAdapter;

    private String auvcode;

    private EditText checkDataEditSpeed;
    private EditText checkDataEditDepth;
    private EditText checkDataLatitude;
    private EditText checkDataLongtitude;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.checktaskdata_table_activity);

        initViews();

        prepareClubData();

        setUpRecyclerView();

        rvClub.addOnScrollListener(new RecyclerView.OnScrollListener()
        {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy)
            {
                super.onScrolled(recyclerView, dx, dy);

                scrollX += dx;

                headerScroll.scrollTo(scrollX, 0);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState)
            {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });
    }

    private void initViews()
    {
        /*
        view = getLayoutInflater().inflate(R.layout.checkdata_dialog, null);

        checkDataLatitude = view.findViewById(R.id.checkdata_latitude);
        checkDataLongtitude = view.findViewById(R.id.checkdata_longtitude);
        checkDataEditSpeed = view.findViewById(R.id.checkdata_speed);
        checkDataEditDepth = view.findViewById(R.id.checkdata_depth);
        */
        rvClub = findViewById(R.id.rvClub);
        headerScroll = findViewById(R.id.headerScroll);
        //createMarkerDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clubList.clear();
        clubList = null;
    }

    /**
     * Prepares dummy data
     */
    private void prepareClubData()
    {
        clubList = new ArrayList<>();
        auvcode = getIntent().getStringExtra("IMEI");
        String GPSINFO = DBHelperSend.getInstance().getGpsInfo(auvcode);
        if (GPSINFO != null) {
            String[] processInfo = GPSINFO.split("\n");
            for(String line : processInfo) {
                String[] mSplit = line.split(":");
                String taskPoint = mSplit[0];
                String[] contents = mSplit[1].split(",");
                clubList.add(new Club(taskPoint + "-任务点", contents[0], contents[1], contents[2], contents[3]));
            }
        }
    }

    /**
     * Handles RecyclerView for the action
     */
    private void setUpRecyclerView() {
        clubAdapter = new ClubAdapter(CheckData.this, clubList);

        FixedGridLayoutManager manager = new FixedGridLayoutManager();
        manager.setTotalColumnCount(1);
        rvClub.setLayoutManager(manager);
        rvClub.setAdapter(clubAdapter);
        rvClub.addItemDecoration(new DividerItemDecoration(CheckData.this, DividerItemDecoration.VERTICAL));
        rvClub.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {

            @Override
            public void onLongClick(View view, int position) {
                mPosition = position;
                headerDataDialog = null;
                createHeaderDataDialog();
                checkDataEditSpeed = headerDataDialog.getInflatedView().findViewById(R.id.checkdata_speed);
                checkDataEditDepth = headerDataDialog.getInflatedView().findViewById(R.id.checkdata_depth);
                checkDataLatitude = headerDataDialog.getInflatedView().findViewById(R.id.checkdata_latitude);
                checkDataLongtitude = headerDataDialog.getInflatedView().findViewById(R.id.checkdata_longtitude);
                checkDataEditSpeed.setText(clubList.get(mPosition).speed);
                checkDataEditDepth.setText(clubList.get(mPosition).depth);
                checkDataLatitude.setText(clubList.get(mPosition).latitude);
                checkDataLongtitude.setText(clubList.get(mPosition).longtitude);
                headerDataDialog.show();
            }
        }));
    }

    /*
    private void createMarkerDialog() {
        alertDialog = new AlertDialog.Builder(CheckData.this)
                .setTitle("请输入该点处需要的航行参数")
                .setView(view)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        clubList.get(mPosition).latitude  = checkDataLatitude.getText().toString();
                        clubList.get(mPosition).longtitude = checkDataLongtitude.getText().toString();
                        clubList.get(mPosition).speed = checkDataEditSpeed.getText().toString();
                        clubList.get(mPosition).depth = checkDataEditDepth.getText().toString();

                        clubAdapter = new ClubAdapter(CheckData.this, clubList);
                        rvClub.setAdapter(clubAdapter);
                        alertDialog.dismiss();
                    }
                }).create();
    }
    */

    private void createHeaderDataDialog() {
        headerDataDialog = new HeaderDialog(this);
        headerDataDialog.setColor(getResources().getColor(R.color.Control3)) // Sets the header background color
                .setElevation(false) // Sets the header elevation, true by default
                .setIcon(getResources().getDrawable(R.drawable.ic_content_paste_black_24dp)) // Sets the dialog icon image
                .setTitle(getResources().getString(R.string.addparameter)) // Sets the dialog title
                .setMessage("请在下面修改" + clubList.get(mPosition).taskPoint + "的数据") // Sets the dialog message
                .justifyContent(true) // Justifies the message text, false by default
                .setTitleColor(Color.parseColor("#212121")) // Sets the header title text color
                .setIconColor(Color.parseColor("#212121")) // Sets the header icon color
                .setTitleGravity(Gravity.CENTER_HORIZONTAL) // Sets the header title text gravity
                .setMessageGravity(Gravity.CENTER_HORIZONTAL) // Sets the message text gravity
                .setTitleMultiline(false) // Multiline header title text option, true by default
                .setView(R.layout.checkdata_dialog) // Set custom view to the dialog (only possible via layout resource)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        clubList.get(mPosition).latitude  = checkDataLatitude.getText().toString();
                        clubList.get(mPosition).longtitude = checkDataLongtitude.getText().toString();
                        clubList.get(mPosition).speed = checkDataEditSpeed.getText().toString();
                        clubList.get(mPosition).depth = checkDataEditDepth.getText().toString();
                        clubAdapter = new ClubAdapter(CheckData.this, clubList);
                        rvClub.setAdapter(clubAdapter);
                        //dbHelperSend.deleteOperation(db);
                        int length = clubList.size();
                        StringBuffer sb = new StringBuffer();
                        FixTaskMapActivity fixTaskMapActivity = FixTaskMapActivity.getInstance();
                        TaskContainer mTaskContainer = fixTaskMapActivity.taskContainer;
                        fixTaskMapActivity.baiduMap.clear();
                        fixTaskMapActivity.refreshDataWithoutLoad();
                        for (int i = 0; i < length - 1; i ++) {
                            String pointIDLatitude = clubList.get(i).latitude;
                            String pointIDLongtitude = clubList.get(i).longtitude;
                            String pointIDSpeed = clubList.get(i).speed;
                            String pointIDDepth = clubList.get(i).depth;
                            LatLng point = new LatLng(Double.valueOf(pointIDLatitude),Double.valueOf(pointIDLongtitude));
                            fixTaskMapActivity.addMissionPointToMapWithoutLoad(gpsToBaidu(point), point);
                            sb.append(clubList.get(i).taskPoint.split("-")[0] + ":" + pointIDLatitude + "," + pointIDLongtitude + "," + pointIDSpeed + "," + pointIDDepth + "\n");
                        }
                        String pointIDLatitude = clubList.get(length - 1).latitude;
                        String pointIDLongtitude = clubList.get(length - 1).longtitude;
                        String pointIDSpeed = clubList.get(length - 1).speed;
                        String pointIDDepth = clubList.get(length - 1).depth;
                        LatLng point = new LatLng(Double.valueOf(pointIDLatitude),Double.valueOf(pointIDLongtitude));
                        fixTaskMapActivity.addMissionPointToMapWithoutLoad(gpsToBaidu(point), point);
                        sb.append(clubList.get(length - 1).taskPoint.split("-")[0] + ":" + pointIDLatitude + "," + pointIDLongtitude + "," + pointIDSpeed + "," + pointIDDepth);
                        DBHelperSend.getInstance().addInfoByIMEI(auvcode,sb.toString());
                        if (mTaskContainer != null) {
                            mTaskContainer.clear();
                        }
                        mTaskContainer = new TaskContainer();
                        String GPSINFO = DBHelperSend.getInstance().getGpsInfo(auvcode);
                        System.out.println("GPSINFO: " + GPSINFO);
                        if (GPSINFO != null) {
                            mTaskContainer.loadData(GPSINFO);
                        }
                        System.out.println("mTaskContainer size: " + mTaskContainer.getTaskSize());
                        toastMsg("完成" + clubList.get(mPosition).taskPoint + "的修改");
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).create();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    private void toastMsg(final String msg) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private LatLng gpsToBaidu(LatLng point) {
        CoordinateConverter converter = new CoordinateConverter();
        converter.from(CoordinateConverter.CoordType.GPS);
        converter.coord(point);
        LatLng changePoint = converter.convert();
        return changePoint;
    }
}
